package com.pow.service.impl;

import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.pow.entity.Role;
import com.pow.repository.RoleRepository;
import com.pow.service.RoleService;
import com.pow.util.FenyeUtil;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;
	public FenyeUtil<Role> getAllRolesByRole(Role r,Pageable pageable,Integer page,Integer limit) {
		
		FenyeUtil<Role> f=new FenyeUtil<Role>();//生成分页工具类
		pageable=PageRequest.of(page-1, limit);
		Page<Role> role=  roleRepository.findAll(get(r),pageable);
		f.setPage(page);//把page传入
		f.setLimit(limit);
		f.setData(role.getContent());
		f.setCount((int)role.getTotalElements());
		return f;
	}
public Specification<Role> get(Role r){
		
		return new Specification<Role>() {
			
			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate predicate=criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if(!StringUtils.isEmpty(r.getName())) {
					expressions.add(criteriaBuilder.like(root.get("name"), "%"+r.getName()+"%"));
				}					
				return predicate;
			}
		};
		
	}
	@Override
	public String updateRole(Role r) {
		try {
			roleRepository.save(r);
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "修改失败";
		}
		
	}

	@Override
	public String deleteRoleById(String id) {
		try {
			roleRepository.deleteById(id); 
			return "删除成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "删除失败";
		}
	}
	@Override
	public String addRole(Role r) {
		try {
			r.setId(UUID.randomUUID().toString());//设置uuid
			roleRepository.save(r);
			
			return "添加成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "添加失败";
		}
	}

}
